using BP.Umb.Logic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.propertytype;
using umbraco.DataLayer;

namespace BP.Umb.Dashboard.MemberAdmin
{
    public partial class MemberAdminUserControl : UserControl
    {
        protected const string SearchMode_Search = "1";
        protected const string SearchMode_Export = "2";
        protected const string SearchMode_GroupFilter = "3";
        protected const string Operation_Delete = "1";
        protected const string Operation_Export = "2";
        protected const string Operation_Regroup = "3";
        protected List<MemberAdminUserControl.VisualGroup> m_groupList;
        protected List<MemberAdminUserControl.VisualGroup> m_typeList;
        protected List<MemberAdminUserControl.VisualGroup> m_typeFieldsList;
        protected IEnumerable<MemberUtils.VisualMember> m_members;
        protected Config m_bpConfig;

        protected bool QueryPerformed
        {
            get
            {
                string str = "";
                if (this.Session["QueryPerformed"] != null)
                    str = (string)this.Session["QueryPerformed"];
                return str == "1";
            }
            set
            {
                if (value)
                    this.Session["QueryPerformed"] = (object)"1";
                else
                    this.Session["QueryPerformed"] = (object)"0";
            }
        }

        protected bool SkipHtmlEncodingContent
        {
            get
            {
                string str = "";
                if (this.Session["SkipHtmlEncodingContent"] != null)
                    str = (string)this.Session["SkipHtmlEncodingContent"];
                return str == "1";
            }
            set
            {
                if (value)
                    this.Session["SkipHtmlEncodingContent"] = (object)"1";
                else
                    this.Session["SkipHtmlEncodingContent"] = (object)"0";
            }
        }

        protected MemberAdminUserControl.OperationType CurrentOperation
        {
            get
            {
                string str = "";
                if (this.Session["CurrentOperation"] != null)
                    str = (string)this.Session["CurrentOperation"];
                switch (str)
                {
                    case "1":
                        return MemberAdminUserControl.OperationType.Delete;
                    case "2":
                        return MemberAdminUserControl.OperationType.Export;
                    case "3":
                        return MemberAdminUserControl.OperationType.Regroup;
                    default:
                        return MemberAdminUserControl.OperationType.NA;
                }
            }
            set
            {
                switch (value)
                {
                    case MemberAdminUserControl.OperationType.Delete:
                        this.Session["CurrentOperation"] = (object)"1";
                        break;
                    case MemberAdminUserControl.OperationType.Export:
                        this.Session["CurrentOperation"] = (object)"2";
                        break;
                    case MemberAdminUserControl.OperationType.Regroup:
                        this.Session["CurrentOperation"] = (object)"3";
                        break;
                    default:
                        this.Session["CurrentOperation"] = (object)"";
                        break;
                }
            }
        }

        protected MemberAdminUserControl.SearchModeType SearchMode
        {
            get
            {
                string str = "";
                if (this.Session["SearchMode"] != null)
                    str = (string)this.Session["SearchMode"];
                switch (str)
                {
                    case "1":
                        return MemberAdminUserControl.SearchModeType.Search;
                    case "3":
                        return MemberAdminUserControl.SearchModeType.GroupFilter;
                    default:
                        return MemberAdminUserControl.SearchModeType.NA;
                }
            }
            set
            {
                switch (value)
                {
                    case MemberAdminUserControl.SearchModeType.Search:
                        this.Session["SearchMode"] = (object)"1";
                        break;
                    case MemberAdminUserControl.SearchModeType.GroupFilter:
                        this.Session["SearchMode"] = (object)"3";
                        break;
                    default:
                        this.Session["SearchMode"] = (object)"";
                        break;
                }
            }
        }

        public IEnumerable<MemberUtils.VisualMember> Members
        {
            get
            {
                if (this.m_members == null)
                {
                    if (this.SearchMode == MemberAdminUserControl.SearchModeType.GroupFilter)
                        this.m_members = (IEnumerable<MemberUtils.VisualMember>)MemberUtils.GetMembersByGroup(this.GetFilterGroupSelection(), this.bpConfig.SearchProvider, this.ReverseFilterCheckBox.Checked);
                    else if (this.SearchMode == MemberAdminUserControl.SearchModeType.Search)
                    {
                        MemberUtils.SearchFieldType sft;
                        switch (this.ListBoxListTypeFields.SelectedIndex)
                        {
                            case 0:
                                sft = MemberUtils.SearchFieldType.Name;
                                break;
                            case 1:
                                sft = MemberUtils.SearchFieldType.Email;
                                break;
                            default:
                                sft = MemberUtils.SearchFieldType.Custom;
                                break;
                        }
                        MemberType byAlias = MemberType.GetByAlias(this.DropDownListTypes.SelectedValue);
                        if (byAlias != null)
                        {
                            PropertyType propertyType = ((ContentType)byAlias).getPropertyType(this.ListBoxListTypeFields.SelectedValue);
                            this.m_members = (IEnumerable<MemberUtils.VisualMember>)MemberUtils.GetMembersBySearch(this.TextBoxSearchQuery.Text, this.bpConfig.SearchProvider, sft, byAlias, propertyType);
                        }
                    }
                    if (this.m_members == null)
                        this.m_members = (IEnumerable<MemberUtils.VisualMember>)new List<MemberUtils.VisualMember>();
                }
                return this.m_members;
            }
        }

        public Config bpConfig
        {
            get
            {
                if (this.m_bpConfig == null)
                    this.m_bpConfig = new Config();
                return this.m_bpConfig;
            }
        }

        protected void InitGroupList()
        {
            IRecordsReader irecordsReader = umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("SELECT text as Name FROM umbracoNode WHERE (nodeObjectType = '366e63b9-880f-4e13-a61c-98069b029728')", new IParameter[0]);
            if (this.m_groupList == null)
                this.m_groupList = new List<MemberAdminUserControl.VisualGroup>();
            if (this.m_groupList.Count == 0)
            {
                while (irecordsReader.Read())
                    this.m_groupList.Add(new MemberAdminUserControl.VisualGroup(irecordsReader.GetString("Name")));
            }
            this.BindGroupDatasource(this.MemberGroupListBox);
            this.BindGroupDatasource(this.ListBoxAddGroup);
            this.BindGroupDatasource(this.ListBoxRemoveGroup);
            irecordsReader.Close();
        }

        protected void InitTypeList()
        {
            if (this.m_typeList == null)
                this.m_typeList = new List<MemberAdminUserControl.VisualGroup>();
            else
                this.m_typeList.Clear();
            foreach (ContentType contentType in MemberType.GetAll)
                this.m_typeList.Add(new MemberAdminUserControl.VisualGroup(contentType.Alias));
            this.BindMemberTypes();
        }

        protected void InitTypeFieldsList()
        {
            if (this.m_typeFieldsList == null)
                this.m_typeFieldsList = new List<MemberAdminUserControl.VisualGroup>();
            else
                this.m_typeFieldsList.Clear();
            string selectedValue = this.DropDownListTypes.SelectedValue;
            if (!(selectedValue != ""))
                return;
            MemberType byAlias = MemberType.GetByAlias(selectedValue);
            if (byAlias != null)
            {
                this.m_typeFieldsList.Add(new MemberAdminUserControl.VisualGroup("Name"));
                this.m_typeFieldsList.Add(new MemberAdminUserControl.VisualGroup("Email"));
                if (Member.InUmbracoMemberMode() && this.bpConfig.SearchProvider == "umbraconative")
                {
                    using (List<PropertyType>.Enumerator enumerator = ((ContentType)byAlias).PropertyTypes.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                            this.m_typeFieldsList.Add(new MemberAdminUserControl.VisualGroup(enumerator.Current.Alias));
                    }
                }
            }
            this.BindMemberTypeFields();
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            this.InitGroupList();
            this.InitTypeList();
            this.InitTypeFieldsList();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.LabelMemberCount.Text = "";
            if (!this.IsPostBack)
            {
                try
                {
                    this.BindDataGrid();
                }
                catch (Exception ex)
                {
                    this.Response.Write("Unable to bind data: " + ((object)ex).ToString());
                    throw new Exception("Unable to bind data: " + ((object)ex).ToString());
                }
                this.ResultGrid.AllowPaging = this.bpConfig.EnablePaging;
                this.ResultGrid.PageSize = this.bpConfig.PageSize;
            }
            this.LabelMemberCount.Text = "Number of members found: " + (object)Enumerable.Count<MemberUtils.VisualMember>(this.Members);
        }

        protected void BindGroupDatasource(ListBox lb)
        {
            lb.DataSource = (object)this.m_groupList;
            lb.DataTextField = "Name";
            lb.DataValueField = "Name";
            lb.DataBind();
            lb.Visible = true;
        }

        protected void BindMemberTypes()
        {
            this.DropDownListTypes.DataSource = (object)this.m_typeList;
            this.DropDownListTypes.DataTextField = "Name";
            this.DropDownListTypes.DataValueField = "Name";
            this.DropDownListTypes.DataBind();
            this.DropDownListTypes.Visible = true;
        }

        protected void BindMemberTypeFields()
        {
            this.ListBoxListTypeFields.DataSource = (object)this.m_typeFieldsList;
            this.ListBoxListTypeFields.DataTextField = "Name";
            this.ListBoxListTypeFields.DataValueField = "Name";
            this.ListBoxListTypeFields.DataBind();
            this.ListBoxListTypeFields.Visible = true;
        }

        protected List<MemberUtils.VisualMember> GetMemberSelection()
        {
            List<MemberUtils.VisualMember> list = new List<MemberUtils.VisualMember>();
            int num = 0;
            foreach (GridViewRow gridViewRow in this.ResultGrid.Rows)
            {
                if (this.CheckBoxSelectAll.Checked || ((CheckBox)gridViewRow.FindControl("chkSelection")).Checked)
                {
                    list.Add(new MemberUtils.VisualMember(gridViewRow.Cells[1].Text, gridViewRow.Cells[3].Text)
                    {
                        Email = gridViewRow.Cells[4].Text,
                        LoginName = gridViewRow.Cells[2].Text
                    });
                    ++num;
                }
            }
            return list;
        }

        protected string ExportMemberSelection()
        {
            this.Response.Clear();
            this.Response.Buffer = true;
            this.Response.AddHeader("content-disposition", "attachment;filename=bpMemberAdminExport.csv");
            this.Response.Charset = "";
            this.Response.ContentType = "application/text";
            this.SkipHtmlEncodingContent = true;
            this.ResultGrid.AllowPaging = false;
            this.BindDataGrid();
            this.SkipHtmlEncodingContent = false;
            StringBuilder stringBuilder = new StringBuilder();
            for (int index = 0; index < this.ResultGrid.HeaderRow.Cells.Count; ++index)
                stringBuilder.Append(this.ResultGrid.HeaderRow.Cells[index].Text + this.TextBoxExportSeparator.Text);
            stringBuilder.Append("\r\n");
            foreach (GridViewRow gridViewRow in this.ResultGrid.Rows)
            {
                if (this.CheckBoxSelectAll.Checked || ((CheckBox)gridViewRow.FindControl("chkSelection")).Checked)
                {
                    for (int index = 0; index < gridViewRow.Cells.Count; ++index)
                        stringBuilder.Append(this.Server.HtmlDecode(gridViewRow.Cells[index].Text) + this.TextBoxExportSeparator.Text);
                    stringBuilder.Append("\r\n");
                }
            }
            this.Response.Output.Write(((object)stringBuilder).ToString());
            this.Response.Flush();
            this.Response.End();
            return "Member selection export to 'bpMemberAdminExport.csv' done.";
        }

        protected List<string> GetFilterGroupSelection()
        {
            List<string> list = new List<string>();
            foreach (ListItem listItem in this.MemberGroupListBox.Items)
            {
                if (listItem.Selected)
                    list.Add(listItem.Text);
            }
            return list;
        }

        protected string[] GetRegroupAddSelection()
        {
            ArrayList arrayList = new ArrayList();
            foreach (ListItem listItem in this.ListBoxAddGroup.Items)
            {
                if (listItem.Selected)
                    arrayList.Add((object)listItem.Text);
            }
            return (string[])arrayList.ToArray(typeof(string));
        }

        protected string[] GetRegroupRemoveSelection()
        {
            ArrayList arrayList = new ArrayList();
            foreach (ListItem listItem in this.ListBoxRemoveGroup.Items)
            {
                if (listItem.Selected)
                    arrayList.Add((object)listItem.Text);
            }
            return (string[])arrayList.ToArray(typeof(string));
        }

        protected void BindDataGrid()
        {
            if (this.QueryPerformed)
                this.ResultGrid.DataSource = (object)this.Members;
            else if (Member.InUmbracoMemberMode())
                this.ResultGrid.DataSource = (object)new List<MemberUtils.VisualMember>();
            else
                this.ResultGrid.DataSource = (object)new List<MemberUtils.VisualMember>();
            this.ResultGrid.DataBind();
        }

        protected void RenderConfirmPage()
        {
            this.MultiView1.ActiveViewIndex = 1;
            List<MemberUtils.VisualMember> memberSelection = this.GetMemberSelection();
            this.BtnConfirmOperation.Enabled = true;
            string str;
            if (memberSelection.Count <= 0)
            {
                str = "<i>&lt;No members selected&gt;</i>";
                this.BtnConfirmOperation.Enabled = false;
            }
            else
            {
                str = "<p>Selection contains:</p>";
                foreach (MemberUtils.VisualMember visualMember in memberSelection)
                    str = str + visualMember.Name + "<br/>";
            }
            this.LabelConfirmMessage.Text = str;
        }

        protected void PerformAndRenderOperationPage()
        {
            List<MemberUtils.VisualMember> memberSelection = this.GetMemberSelection();
            string[] regroupAddSelection = this.GetRegroupAddSelection();
            string[] regroupRemoveSelection = this.GetRegroupRemoveSelection();
            string str;
            switch (this.CurrentOperation)
            {
                case MemberAdminUserControl.OperationType.Delete:
                    str = MemberUtils.DeleteMembers(memberSelection);
                    break;
                case MemberAdminUserControl.OperationType.Export:
                    str = this.ExportMemberSelection();
                    break;
                case MemberAdminUserControl.OperationType.Regroup:
                    str = MemberUtils.RegroupMembers(memberSelection, regroupAddSelection, regroupRemoveSelection);
                    break;
                default:
                    str = "Internal error !!";
                    break;
            }
            this.MultiView1.ActiveViewIndex = 2;
            this.LabelOperationStatus.Text = str;
        }

        protected void ButtonGetData_Click(object sender, EventArgs e)
        {
            this.ResultGrid.Visible = true;
            this.SearchMode = MemberAdminUserControl.SearchModeType.GroupFilter;
            this.m_members = (IEnumerable<MemberUtils.VisualMember>)null;
            this.QueryPerformed = true;
            this.BindDataGrid();
        }

        protected void ButtonSearch_Click(object sender, EventArgs e)
        {
            this.ResultGrid.Visible = true;
            this.SearchMode = MemberAdminUserControl.SearchModeType.Search;
            this.m_members = (IEnumerable<MemberUtils.VisualMember>)null;
            this.QueryPerformed = true;
            this.BindDataGrid();
        }

        protected void BtnApplyDelete_Click(object sender, EventArgs e)
        {
            this.CurrentOperation = MemberAdminUserControl.OperationType.Delete;
            this.RenderConfirmPage();
        }

        protected void BtnApplyExport_Click(object sender, EventArgs e)
        {
            this.CurrentOperation = MemberAdminUserControl.OperationType.Export;
            this.PerformAndRenderOperationPage();
        }

        protected void BtnApplyGroupChanges_Click(object sender, EventArgs e)
        {
            this.CurrentOperation = MemberAdminUserControl.OperationType.Regroup;
            this.RenderConfirmPage();
        }

        protected void BtnBackFromConfirm_Click(object sender, EventArgs e)
        {
            this.MultiView1.ActiveViewIndex = 0;
        }

        protected void BtnConfirmOperation_Click(object sender, EventArgs e)
        {
            this.PerformAndRenderOperationPage();
        }

        protected void BtnOperationStatusOk_Click(object sender, EventArgs e)
        {
            this.MultiView1.ActiveViewIndex = 0;
            this.ListBoxAddGroup.ClearSelection();
            this.ListBoxRemoveGroup.ClearSelection();
            this.MemberGroupListBox.ClearSelection();
            this.LabelConfirmMessage.Text = "";
            this.LabelOperationStatus.Text = "";
            this.CurrentOperation = MemberAdminUserControl.OperationType.NA;
            this.QueryPerformed = false;
            this.m_members = (IEnumerable<MemberUtils.VisualMember>)null;
            this.BindDataGrid();
        }

        protected void ResultGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!Member.InUmbracoMemberMode() || this.SkipHtmlEncodingContent || (e.Row.RowIndex < 0 || e.Row.Cells.Count < 3))
                return;
            e.Row.Cells[3].Text = "<a href=\"members/EditMember.aspx?id=" + e.Row.Cells[1].Text + "\">" + e.Row.Cells[3].Text + "</a>";
        }

        protected void ResultGrid_PageIndexChanging(object source, GridViewPageEventArgs e)
        {
            this.ResultGrid.PageIndex = e.NewPageIndex;
            this.BindDataGrid();
        }

        protected void ResultGrid_SortCommand(object source, GridViewSortEventArgs e)
        {
        }

        protected void ResultGrid_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Pager && this.ResultGrid.PageIndex > 0)
            {
                LinkButton linkButton = new LinkButton();
                linkButton.Text = "< Previous   ";
                linkButton.Click += new EventHandler(this.lbBack_Click);
                e.Row.Controls[0].Controls.AddAt(0, (Control)linkButton);
            }
            if (e.Row.RowType != DataControlRowType.Pager || this.ResultGrid.PageIndex >= this.ResultGrid.PageCount - 1)
                return;
            LinkButton linkButton1 = new LinkButton();
            linkButton1.Text = "   Next >";
            linkButton1.Click += new EventHandler(this.lbForward_Click);
            e.Row.Controls[0].Controls.AddAt(e.Row.Controls[0].Controls.Count, (Control)linkButton1);
        }

        protected void lbBack_Click(object sender, EventArgs e)
        {
            this.ResultGrid.PageIndex = this.ResultGrid.PageIndex - 1;
            this.BindDataGrid();
        }

        protected void lbForward_Click(object sender, EventArgs e)
        {
            this.ResultGrid.PageIndex = this.ResultGrid.PageIndex + 1;
            this.BindDataGrid();
        }

        protected void ResultGrid_PreRender(object sender, EventArgs e)
        {
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
        }

        protected void DropDownListTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.InitTypeFieldsList();
        }

        protected void DropDownListTypesFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        protected void ResultGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        protected class VisualGroup
        {
            public string Name { get; set; }

            public VisualGroup(string name)
            {
                this.Name = name;
            }
        }

        protected enum SearchModeType
        {
            NA,
            Search,
            GroupFilter,
        }

        protected enum OperationType
        {
            NA,
            Delete,
            Export,
            Regroup,
        }
    }
}
